package org.opu.gui.component;

import doc2db.UserProp;
import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.*;

/**
 * Component to be used as tabComponent;
 * Contains a JLabel to show the text and 
 * a JButton to close the tab it belongs to 
 */
public class ButtonTabComponent extends JPanel {

    private final JTabbedPane pane;
    private int tabbedNum = 0;
    private Status status;

    public ButtonTabComponent(final JTabbedPane pane, int tab, Status status) {
        super(new FlowLayout(FlowLayout.LEFT, 0, 0));

        if (pane == null) {
            throw new NullPointerException("TabbedPane is null");
        }

        this.status = status;
        this.pane = pane;
        this.tabbedNum = tab;

        setOpaque(false);

        //make JLabel read titles from JTabbedPane
        JLabel label = new JLabelImpl(pane);

        //add icon
        add(new JLabel(pane.getIconAt(tabbedNum)));

        //add label
        add(label);
        
        //add more space between the label and the button
        label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
        label.setFont(UserProp.paneFont);

        
        //create close button
        JButton button = new TabButton();

        Dimension btnsz = button.getPreferredSize();
        int tabCount = pane.getTabCount();
        int paneWdth = pane.getBounds().width;

        int w = paneWdth / tabCount - 24;
        int h = btnsz.height + 2;

        // add spase betwen buuton and label
        JPanel spase = new JPanel(){

            @Override
            public void paintComponent(Graphics g) {
            }

        };
        int lw = stringWidth(getTabText(this.tabbedNum), label.getFont());
        int iw = label.getPreferredSize().width;
        Dimension d = new Dimension(w - lw - btnsz.width - iw, btnsz.height);
        spase.setPreferredSize(d);
        add(spase);

        //add close button
        add(button);
        
        //add more space to the top of the component
        setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
        setPreferredSize(new Dimension(w, h));
    }

    /**
     * Get text on pane tab with curent component on it
     * @return text on pane tab with curent component on it
     */
    private String getTabText() {
        int i = pane.indexOfTabComponent(ButtonTabComponent.this);
        return this.getTabText(i);
    }

    /**
     *  text on pane tab with i nuber
     * @param i number of tab
     * @return  text on pane tab with i nuber
     */
    private String getTabText(int i) {
        if (i != -1) {
            String s = pane.getTitleAt(i);
            if (s.length() < 15) {
                return s;
            } else {
                return s.substring(0, 13) + "..";
            }
        }
        return null;
    }

    /**
     *  Return string width for font f and string s, using DefaultToolkit
     * and FontMetrics
     * @param s string
     * @param f font
     * @return  string width for font f and string s
     * @see Toolkit
     * @see FontMetrics
     */
    private int stringWidth(String s, Font f){
        if (f == null || s == null){
            return 10;
        }

        return Toolkit.getDefaultToolkit().getFontMetrics(f).stringWidth(s);
    }

    private class TabButton extends JButton implements ActionListener {

        public TabButton() {
            int size = 17;
            setPreferredSize(new Dimension(size, size));
            setToolTipText("close this tab");
            //Make the button looks the same for all Laf's
            setUI(new BasicButtonUI());
            //Make it transparent
            setContentAreaFilled(false);
            //No need to be focusable
            setFocusable(false);
            setBorder(BorderFactory.createEtchedBorder());
            setBorderPainted(false);
            //Making nice rollover effect
            //we use the same listener for all buttons
            addMouseListener(buttonMouseListener);
            setRolloverEnabled(true);
            //Close the proper tab by clicking the button
            addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int i = pane.indexOfTabComponent(ButtonTabComponent.this);
            if (i != -1) {
                //pane.remove(i);
                status.elementRemoved(pane.getTitleAt(i));
            }
        }

        //we don't want to update UI for this button
        @Override
        public void updateUI() {
        }

        //paint the cross
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            //shift the image for pressed buttons
            if (getModel().isPressed()) {
                g2.translate(1, 1);
            }
            g2.setStroke(new BasicStroke(2));
            g2.setColor(Color.BLACK);
            if (getModel().isRollover()) {
                g2.setColor(Color.MAGENTA);
            }
            int delta = 6;
            g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
            g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
            /*g2.drawImage(PanelImage.getCloseTabeImage(), 0, 0, null);*/
            g2.dispose();
        }
    }
    
    private final static MouseListener buttonMouseListener = new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            Component component = e.getComponent();
            if (component instanceof AbstractButton) {
                AbstractButton button = (AbstractButton) component;
                button.setBorderPainted(true);
            }
        }

        @Override
        public void mouseExited(MouseEvent e) {
            Component component = e.getComponent();
            if (component instanceof AbstractButton) {
                AbstractButton button = (AbstractButton) component;
                button.setBorderPainted(false);
            }
        }
    };

    class JLabelImpl extends JLabel {

        private final JTabbedPane pane;

        public JLabelImpl(JTabbedPane pane) {
            this.pane = pane;
        }

        @Override
        public String getText() {
            return getTabText();
        }
    }
}


